package com.mobile.pilihsaya;

import java.net.URI;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;


import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlrpc.android.XMLRPCClient;

import android.content.Context;
import android.util.Log;

public class ServiceHelper {
	
	private static final int NULL = 0;
	private URI uri = URI.create("http://202.149.81.4/");
	private XMLRPCClient client = new XMLRPCClient(uri);
	
	public boolean daftar(Context contex, String nama, String email, String alamat){
		
		
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		
		try {
			client.call("reg", nama, email, alamat);
			//JSONArray jsonArray = new JSONArray("[" + text + "]");
			//JSONArray innerJsonArray = jsonArray.getJSONArray(0);
			//JSONObject json = innerJsonArray.getJSONObject(0);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		
		
		
		
	}
	
	public static final String md5(final String toEncrypt) {
	    try {
	        final MessageDigest digest = MessageDigest.getInstance("md5");
	        digest.update(toEncrypt.getBytes());
	        final byte[] bytes = digest.digest();
	        final StringBuilder sb = new StringBuilder();
	        for (int i = 0; i < bytes.length; i++) {
	            sb.append(String.format("%02X", bytes[i]));
	        }
	        return sb.toString().toLowerCase();
	    } catch (Exception exc) {
	        return ""; // Impossibru!
	    }
	}
	
	public boolean login(Context contex, String email, String pass){
		
		DBClass db = new DBClass(contex);
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		
		try {
			String text = (String) client.call("login", email, pass);
			JSONArray jsonArray = new JSONArray("[" + text + "]");
			JSONArray innerJsonArray = jsonArray.getJSONArray(0);
			JSONObject json = innerJsonArray.getJSONObject(0);
			String stsUsr = json.getString("email");
			String stsPwd = json.getString("pass");
//			String stsPass = md5(stsPwd);
//			KeyGenerator.getInstance("AES");
			
			if (stsUsr.equals(email) && stsPwd.equals(md5(pass))){
				
				db.InsertRelawan(new Login(NULL, json.getString("nama"), json.getString("email"),
						json.getString("alamat"),json.getString("pass"),dateFormat.format(date)));
				
				Log.d("Status", "Login");
				return true;
			} else {
				Log.d("Status", "Gagal");
				return false;
			}
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		
		
		
		
	}
	

}
